package org.awenlice.playerdailyshop.config;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import net.minecraft.nbt.CompoundTag;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ConfigHelper {
    private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
    private static final File CONFIG_FILE = new File("config/playerDailyShop.json");
    private static final Logger LOGGER = LogManager.getLogger(); // 添加日志

    /**
     * 检测并生成配置文件
     */
    public static void checkAndGenerateConfig() {
        if (!CONFIG_FILE.exists()) {
            generateDefaultConfig();
        }
    }

    /**
     * 生成默认配置文件
     */
    static class NBT {
        private final Quality quality;
        NBT(Quality q) {
            this.quality = q;
        }

        public Quality getQuality() {
            return quality;
        }
    }
    static class Quality{
        private String effects = "";
        private String quality = "";

        Quality(String effects, String quality) {
            this.effects = effects;
            this.quality = quality;
        }

        public String getEffects() {
            return effects;
        }

        public String getQuality() {
            return quality;
        }
    }

    private static void generateDefaultConfig() {
        ShopConfig config = new ShopConfig();

        // 默认出售物品
        config.sellItems = new ShopConfig.ShopItem[]{
                new ShopConfig.ShopItem("minecraft:diamond", "", 100L, "传说"),
                new ShopConfig.ShopItem("minecraft:emerald", "", 50L, "史诗"),
                new ShopConfig.ShopItem("minecraft:gold_ingot", "", 20L, "罕见"),
                new ShopConfig.ShopItem("minecraft:gold_ingot",  "", 10L, "稀有"),
                new ShopConfig.ShopItem("minecraft:bread",  "{quality_food:{effect:{}, quality:1}}", 10L, "普通"),
                new ShopConfig.ShopItem("minecraft:gold_ingot",  "", 2L, "稀碎")
        };

        // 默认收购物品
        config.buyItems = new ShopConfig.ShopItem[]{
                new ShopConfig.ShopItem("minecraft:diamond", "", 100L, "传说"),
                new ShopConfig.ShopItem("minecraft:emerald", "", 50L, "史诗"),
                new ShopConfig.ShopItem("minecraft:gold_ingot", "", 20L, "罕见"),
                new ShopConfig.ShopItem("minecraft:gold_ingot",  "", 10L, "稀有"),
                new ShopConfig.ShopItem("minecraft:gold_ingot",  "", 10L, "普通"),
                new ShopConfig.ShopItem("minecraft:gold_ingot",  "", 2L, "稀碎")
        };

        // 默认权重
        config.weights = new ShopConfig.weightItem[]{
                new ShopConfig.weightItem("传说", 0.001),
                new ShopConfig.weightItem("史诗", 0.01),
                new ShopConfig.weightItem("罕见", 0.1),
                new ShopConfig.weightItem("稀有", 0.5),
                new ShopConfig.weightItem("普通", 0.75),
                new ShopConfig.weightItem("稀碎", 1)
        };

        try (FileWriter writer = new FileWriter(CONFIG_FILE)) {
            GSON.toJson(config, writer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 加载配置文件
     */
    public static ShopConfig loadConfig() {
        try (FileReader reader = new FileReader(CONFIG_FILE)) {
            ShopConfig config = GSON.fromJson(reader, ShopConfig.class);
            // 读取权重信息
            try {
                ShopConfig.weightItem[] weightItem = config.getWeights();
                ShopConfig.weightItems.addAll(Arrays.asList(weightItem));
            } catch (Exception e) {
                LOGGER.error("Failed to load weight config!", e); // 日志输出
            }

            // 读取出售商品信息
            try {
                ShopConfig.ShopItem[] shopItems = config.getSellItems();
                ShopConfig.sellShopItems.addAll(Arrays.asList(shopItems));
            } catch (Exception e) {
                LOGGER.error("Failed to load sellShop config!", e); // 日志输出
            }

            // 读取购买商品信息
            try {
                ShopConfig.ShopItem[] shopItems = config.getBuyItems();
                ShopConfig.buyShopItems.addAll(Arrays.asList(shopItems));
            } catch (Exception e) {
                LOGGER.error("Failed to load buyShop config!", e); // 日志输出
            }

            // 按照权重将其分类
            for (ShopConfig.weightItem weight: ShopConfig.weightItems){
                ShopConfig.sell.put(weight.name, new ArrayList<>());
                ShopConfig.buy.put(weight.name, new ArrayList<>());
            }

            for (ShopConfig.ShopItem item: ShopConfig.sellShopItems){
                List<ShopConfig.ShopItem> target = ShopConfig.sell.get(item.getWeight());
                target.add(item);
                ShopConfig.sell.put(item.getWeight(), target);
            }

            for (ShopConfig.ShopItem item: ShopConfig.buyShopItems){
                List<ShopConfig.ShopItem> target = ShopConfig.buy.get(item.getWeight());
                target.add(item);
                ShopConfig.buy.put(item.getWeight(), target);
            }

            return GSON.fromJson(reader, ShopConfig.class);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}